// 测试 中间件(middleware)

const express = require('express');

const port = 8080;
const app = express();

app.get('/', (req, resp) => {
    console.log('root');
    resp.send('<h1>' + new Date().toLocaleString() + '</h1>');
});

const myfun1 = (req, resp, next) => {
    console.log('first', req.query);

    // 如果 queryString 中包含 flag 且其取值是 非空字符串
    //测试用例url：http://localhost:8080/select?flag=string
    if (req.query.flag) {
        req.student = {
            id: 1001,
            name: '张三丰',
            gender: '靓仔',
            age: 108
        }
    }

    if (req.student) {
        next();
    } else {
        resp.redirect('/'); // 重定向: 设置状态代码、设置响应头
    }
}

app.use('/select', myfun1);

const myfun2 = (req, resp) => {
    console.log('second');
    let stu = req.student;
    resp.send(stu);
    // throw new Error('不晓得为啥，反正出错了');
}

app.get('/select', myfun2);
//只有当 err 存在时，才运行下面的中间件
const myfun3 = (err, req, resp, next) => {
    console.log('third');
    if (err) {
        console.log(err);
        resp.status(599).send(err.message);
    }
}

app.use('/select', myfun3);

app.listen(port);